<template>
  <el-select-v2
    class="simple-select"
    v-if="editMode"
    v-bind="$attrs"
    clearable
    filterable
    :options="getOptions()"
    @clear="() => $emit('update:modelValue', '')"
  />

  <div class="simple-text" v-else :style="`justify-content: ${textAlign}`">
    <dict-tag v-if="$attrs.modelValue" :type="dictType" :value="$attrs.modelValue" />
    <el-link
      v-if="$attrs.modelValue && showCopy"
      class="copy-link"
      :underline="false"
      @click="copyText(getDictLabel(dictType, $attrs.modelValue as string))"
    >
      <el-icon>
        <DocumentCopy />
      </el-icon>
      <span class="text">{{ t('common.clickCopy') }}</span>
    </el-link>
  </div>
</template>

<script setup lang="ts">
import { useClipboard } from '@vueuse/core'
import { DocumentCopy } from '@element-plus/icons-vue'
import { DICT_TYPE, getDictLabel, getStrDictOptions, StringDictDataType } from '@/utils/dict'

const props = withDefaults(
  defineProps<{
    dictType: DICT_TYPE
    showCopy?: boolean
    textAlign?: string
    disableFunction?: (option: StringDictDataType) => boolean
  }>(),
  {
    showCopy: true,
    textAlign: 'flex-start'
  }
)

const editMode = inject('editMode', true)

const message = useMessage()
const { t } = useI18n()
const { copy } = useClipboard()

const copyText = async (text: string) => {
  try {
    await copy(text)
    message.success(t('common.copySuccess'))
  } catch (e) {
    message.error(t('common.copyError'))
  }
}

const getOptions = () => {
  const options = getStrDictOptions(props.dictType)
  if (props.disableFunction) {
    return options.map((option) => {
      return { ...option, disabled: props.disableFunction!(option) }
    })
  }
  return options
}
</script>

<style scoped lang="scss">
.simple-select {
  :deep(.el-select__wrapper) {
    border-radius: 0 !important;
    box-shadow: none !important;
    padding: 0 !important;
    border-bottom: 1px solid var(--el-border-color);
  }
}

.simple-text {
  display: flex;
  align-items: center;

  .copy-link {
    visibility: hidden;
    margin-left: 6px;

    .text {
      font-size: 12px;
      visibility: hidden;
    }

    &:hover {
      .text {
        visibility: visible;
      }
    }
  }

  &:hover {
    .copy-link {
      visibility: visible;
    }
  }
}
</style>
